package com.artron.mediaartron.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.artron.baselib.utils.ToastUtil;
import com.artron.baselib.utils.UIUtils;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.schedulers.Schedulers;

import static android.R.attr.action;


/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-11-08.
 */

public class CacheUtils {

    public static String getCacheSize(Context context) {
        long fileSize = 0;

        fileSize += getDirSize(context.getFilesDir());
        fileSize += getDirSize(context.getCacheDir());

        if(isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)){
            File externalCacheDir = getExternalCacheDir(context);//"<sdcard>/Android/data/<package_name>/cache/"
            fileSize += getDirSize(externalCacheDir);
        }

        if (fileSize > 0)
            return formatFileSize(fileSize);
        return "0M";
    }

    /**
     * 获取目录文件大小
     *
     * @param dir
     * @return
     */
    public static long getDirSize(File dir) {
        if (dir == null) {
            return 0;
        }
        if (!dir.isDirectory()) {
            return 0;
        }
        long dirSize = 0;
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                dirSize += file.length();
            } else if (file.isDirectory()) {
                dirSize += file.length();
                dirSize += getDirSize(file); // 递归调用继续统计
            }
        }
        return dirSize;
    }

    /**
     * 判断当前版本是否兼容目标版本的方法
     * @param VersionCode
     * @return
     */
    public static boolean isMethodsCompat(int VersionCode) {
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        return currentVersion >= VersionCode;
    }

    @TargetApi(8)
    public static File getExternalCacheDir(Context context) {

        // return context.getExternalCacheDir(); API level 8

        // e.g. "<sdcard>/Android/data/<package_name>/cache/"

        return context.getExternalCacheDir();
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return B/KB/MB/GB
     */
    public static String formatFileSize(long fileS) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    /**
     * 清除app缓存
     *
     * @param context
     */
    public static void clearAppCache(final Context context, final Action0 action) {
        Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                try {
                    //清除数据缓存
                    clearCacheFolder(context.getFilesDir(),System.currentTimeMillis());
                    clearCacheFolder(context.getCacheDir(),System.currentTimeMillis());
                    //2.2版本才有将应用缓存转移到sd卡的功能
                    if(isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)){
                        clearCacheFolder(CacheUtils.getExternalCacheDir(context),System.currentTimeMillis());
                    }
                    subscriber.onNext(1);
                } catch (Exception e) {
                    e.printStackTrace();
                    subscriber.onNext(-1);
                    subscriber.onError(e);
                } finally {
                    subscriber.onCompleted();
                }
            }
        })
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                if (integer == 1) {
                    action.call();
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                MobclickAgent.reportError(UIUtils.getContext(), throwable);
            }
        });
    }


    /**
     * 清除app缓存
     */
    public static void clearAppCache()
    {
        //清除webview缓存
//        @SuppressWarnings("deprecation")
//        File file = CacheManager.getCacheFileBaseDir();

        //先删除WebViewCache目录下的文件

//        if (file != null && file.exists() && file.isDirectory()) {
//            for (File item : file.listFiles()) {
//                item.delete();
//            }
//            file.delete();
//        }
//        deleteDatabase("webview.db");
//        deleteDatabase("webview.db-shm");
//        deleteDatabase("webview.db-wal");
//        deleteDatabase("webviewCache.db");
//        deleteDatabase("webviewCache.db-shm");
//        deleteDatabase("webviewCache.db-wal");

    }

    /**
     * 清除缓存目录
     * @param dir 目录
     * @param 当前系统时间
     * @return
     */
    private static int clearCacheFolder(File dir, long curTime) {
        int deletedFiles = 0;
        if (dir!= null && dir.isDirectory()) {
            try {
                for (File child:dir.listFiles()) {
                    if (child.isDirectory()) {
                        deletedFiles += clearCacheFolder(child, curTime);
                    }
                    if (child.lastModified() < curTime) {
                        if (child.delete()) {
                            deletedFiles++;
                        }
                    }
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        return deletedFiles;
    }
}
